package cn.tanghom.support.db;

import java.io.Closeable;

public class DynamicDataSourceHolder {
    private static ThreadLocal<String> routeKey = new ThreadLocal<String>();
    /**
     * 获取当前线程的数据源路由的key
     */
    public static String getRouteKey() {
        String key = routeKey.get();
        return key;
    }
    /**
     * 绑定当前线程数据源路由的key 使用完成后必须调用removeRouteKey()方法删除
     */
    public static void setRouteKey(String key) {
    	if(key!=null){
    		routeKey.set(key);
    	}
    	else{
    		routeKey.set("jdbc"); //set default
    	}
    }
    /**
     * 删除与当前线程绑定的数据源路由的key
     */
    public static void removeRouteKey() {
        routeKey.remove();
    }
    
    /**
      try(val db = DynamicDataSourceHolder.active(db_key)){
         leaveMapper.update(entity);
      }
     * @author Hunteron-cp
     *
     */
    public static class Active implements Closeable{
    	String prev;
    	
    	public Active(String key){
    		prev = DynamicDataSourceHolder.getRouteKey();
    		DynamicDataSourceHolder.setRouteKey(key);
    	}
    	
    	public void close(){
    		DynamicDataSourceHolder.setRouteKey(prev);
    	}
    }
    
    public static Active active(String key){
    	return new Active(key);
    }
}